import React, { useEffect, useMemo, useState } from 'react';
import Modals from '@/components/modals/Modals';
import '@/components/work-modal/work.scss';
import { ModalProps } from 'antd';
import { SvgIcon } from '@/components/icon';
import useTable from '@/hooks/use-table';
import { GetCreatedListItem, GetCreatedTemplateItem } from '@/common/types';
import { CircleLoading } from '@/components/loading';
import GradientDiv from '@/components/GradientBox/GradientDiv';
import { Search, Tag } from '@/components/eai-design';
import mcpService from '@/api/services/mcpService';
import { useRouter } from '@/router/hooks';

interface Props extends ModalProps {
  open: boolean;
  onCancel: () => void;
  onOk: (value: GetCreatedTemplateItem) => void;
  selectProvider?: GetCreatedListItem[];
}


const index = ({ onCancel, onOk, selectProvider, ...props }: Props) => {
  const [selected, setSelected] = useState<GetCreatedTemplateItem>();
  const [activeIndex, setActiveIndex] = useState<number>(-1);
  // const router = useNavigate();
  const router = useRouter();
  const {
    tablesValue,
    getTables,
    pagingInfo,
    handleSearchText,
    searchText,
    setTablesValue,
    loading,
    handleSearchTextInit,
  } = useTable<GetCreatedTemplateItem>(mcpService.getTemplateList, {
    page: 1,
    pageSize: 9999,
    searchText: '',
    total: 0,
    offset: -1,
  });

  useEffect(() => {
    if (props.open) {
      handleSearchTextInit('');
      getTables();
    }
  }, [props.open]);

  const handleSelected = (item: GetCreatedTemplateItem) => {
    if (item?.name === selected?.name) {
      setSelected(undefined);
      return;
    }
    setSelected(item);
  };

  const onSubmit = () => {
    if (selected) {
      setSelected(undefined);
      onOk(selected);
    } else {
    }
  };

  const cancel = () => {
    setSelected(undefined);
    onCancel();
  };

  const onToCreated = (obj: GetCreatedTemplateItem) => {
    router.pushQuery('/mcp/orchestration', obj);
  };

  const handleInit = (open: boolean) => {
    console.log('open', open);
    if (!open) {
      // init();
    }
    // if (!open) {
    //   setSelected(undefined);
    // }
  };
  function mouseEvent(e: number) {
    return () => {
      setActiveIndex(e);
    };
  }

  function mouseLeave() {
    return () => {
      setActiveIndex(-1);
    };
  }
  return (
    <Modals
      {...props}
      title="添加MCP工具"
      onCancel={cancel}
      width={950}
      destroyOnHidden
      footer={null}
      afterOpenChange={handleInit}
    >
      <div className='text-start'>
        <Search
          value={searchText}
          className='!w-[240px]'
          onChange={(e) => handleSearchText(e.target.value)}
          placeholder="搜索"
        />
      </div>

      <div
        className={`mt-4 h-[470px] w-full  ${!loading ? 'grid grid-cols-3 grid-rows-3 gap-[16px] overflow-auto' : ''
          }`}
      >
        {loading ? (
          <CircleLoading />
        ) : (
          <React.Fragment>
            <div
              className="jr-step-v2-2 jr2-step-v2-1 create-MCP"
              onClick={() => onToCreated()}
            >
              <SvgIcon icon="work-add" size={30} />
              <div className="word-color  mt-2 text-sm ">
                添加自定义MCP
              </div>
            </div>
            {tablesValue.map((item, index) => (
              <GradientDiv
                showCheck={false}
                onClick={() => handleSelected(item)}
                className={`p-4 boxs box-hover group bg-fill-1`}
                active={false}
                key={index}
                boxShadow={false}
                onMouseEnter={mouseEvent(index)}
                onMouseLeave={mouseLeave()}
              >
                <div className="flex items-center">
                  <div className="w-10 h-10 rounded-md bg-white flex items-center justify-center group-hover:bg-fill-1">
                    <SvgIcon icon={item.avatar} size={24} />
                  </div>
                  <div className="text-truncate ml-4 text-sm font-semibold text-text-5">
                    {item.name}
                    <div className='font-normal'>
                      <Tag key={index}>{item.categoryCN}</Tag>
                    </div>
                  </div>

                </div>
                <div className="text-truncate mt-4 text-xs text-text-4">{item.description}</div>

                {/* 浮窗容器 */}
                <div className="popup-content">
                  <div
                    className="popup-content-child"
                    onClick={(e) => {
                      e.stopPropagation();
                      console.log('创建:', item);
                      onToCreated(item)
                    }}
                  >
                    创建
                  </div>
                </div>
              </GradientDiv>
            ))}
          </React.Fragment>
        )}
      </div>
    </Modals>
  );
};

export default index;
